<?php
namespace Buu\Modules\HaohaoceManager\Lib;
use Exonet\Powerdns\Powerdns;
use Exonet\Powerdns\RecordType;
use Exonet\Powerdns\Resources\ResourceRecord;
use Doraemon\tools\Log;


class Dns{
	private $powerdns ;
	const TTL = 10;
	const SLB_ID = 'lb-2ze1w089z8jbsnscj5zuu';
	const SLB_REGION_ID = 'cn-beijing';
	const SLB_PORT = '80';
	public function __construct(){
		
	}

	public function get($domain_prefix , $root_domain ){
		$cmd = '/usr/local/bin/aliyun  -p product alidns DescribeDomainRecords'
		.' --DomainName '.$root_domain
		.' --RRKeyWord '.$domain_prefix;
		$rs = $this->exec($cmd);
		$rs = json_decode($rs , 1);

		$prefix2domaininfo = array();
		if(isset($rs['DomainRecords']['Record']) && count($rs['DomainRecords']['Record']) > 0){
			foreach($rs['DomainRecords']['Record'] as $row){
				$prefix2domaininfo[$row['RR']] = $row;
			}
		}
		return $prefix2domaininfo;
	}
	public function del($domain_prefix , $root_domain){
		$rows = $this->get($domain_prefix , $root_domain);
		if(isset($rows[$domain_prefix])){
			$RecordId = $rows[$domain_prefix]['RecordId'];
			$cmd = '/usr/local/bin/aliyun  -p product alidns DeleteDomainRecord --RecordId '.$RecordId;
			$rs = $this->exec($cmd);
			$rs = json_decode($rs , 1);
			if($rs['RecordId'] == $RecordId){
				return true;
			}else{
				return false;
			}
		}
		return false;
	}
	public function bind($domain_prefix , $root_domain , $ip){
		$cmd = '/usr/local/bin/aliyun -p product alidns AddDomainRecord'
		.' --DomainName '.$root_domain
		.' --RR '.$domain_prefix
		.' --Type A'
		.' --Value '.$ip;
		$rs = $this->exec($cmd);
		$rs = json_decode($rs , 1);
		if(isset($rs['RecordId'])){
			return true;
		}else{
			return false;
		}
	}

	public function list_slb_name2vserverids($region_id , $slb_id){
		$cmd = '/usr/local/bin/aliyun -p product slb DescribeVServerGroups --RegionId '.$region_id.' --LoadBalancerId '.$slb_id;
		$rs = $this->exec($cmd);
// 		$rs = '{
// 	"RequestId": "A643942E-A2CA-5E2A-934A-4CE71C060B15",
// 	"VServerGroups": {
// 		"VServerGroup": [
// 			{
// 				"AssociatedObjects": {
// 					"Listeners": {
// 						"Listener": []
// 					},
// 					"Rules": {
// 						"Rule": []
// 					}
// 				},
// 				"VServerGroupId": "rsp-2zewunk9r7ws2",
// 				"VServerGroupName": "k8s/91/aaaaa/hhc/c345a7e8736c14ea8b8f92ea104589bfd"
// 			},
// 			{
// 				"AssociatedObjects": {
// 					"Listeners": {
// 						"Listener": []
// 					},
// 					"Rules": {
// 						"Rule": []
// 					}
// 				},
// 				"VServerGroupId": "rsp-2zepetboc5oev",
// 				"VServerGroupName": "k8s/91/hhc-be-4-20220308173256/hhc/c345a7e8736c14ea8b8f92ea104589bfd"
// 			}
// 		]
// 	}
// }';
		$rs = json_decode($rs , 1);

		$aVserverIds = array();
		foreach($rs['VServerGroups']['VServerGroup'] as $row){
			$aVserverIds[$row['VServerGroupName']] = $row['VServerGroupId'];
		}
		return $aVserverIds;
	}
	public function list_slb_ruleinfo_in_rules($region_id , $slb_id , $port){
		$cmd = '/usr/local/bin/aliyun -p product slb DescribeRules --RegionId '.$region_id.' --LoadBalancerId '.$slb_id.' --ListenerPort '.$port;
		$rs = $this->exec($cmd);
// 		$rs = '{
// 	"RequestId": "134F8904-7492-5812-9FDD-5C06C2C70950",
// 	"Rules": {
// 		"Rule": [
// 			{
// 				"Domain": "*.qa51.haohaoce.com",
// 				"ListenerSync": "on",
// 				"RuleId": "rule-2ze5mxhzl2y5c",
// 				"RuleName": "auto_named_rule",
// 				"VServerGroupId": "rsp-2zewunk9r7ws2"
// 			}
// 		]
// 	}
// }';
		$rs = json_decode($rs , 1);
		$aVserverIds = array();
		foreach($rs['Rules']['Rule'] as $row){
			$a = preg_match('/qa([0-9]+)/', $row['Domain'] , $b);
			$aVserverIds[$row['RuleId']] = array(
				'domain_suffix' => $b[1],
				'rule_id' => $row['RuleId'],
				'vserver_id' => $row['VServerGroupId']
			);
		}
		return $aVserverIds;
	}
	public function format_slb_rule($pod_id , $domain_suffix , $vserver_id){
		return '[{"RuleName":"'.$pod_id.'","Domain":"*.qa'.$domain_suffix.'.haohaoce.com","VServerGroupId":"'.$vserver_id.'"}]';
	}
	public function add_slb_forward_rule($region_id , $slb_id , $port , $rule){
		$cmd = '/usr/local/bin/aliyun -p product slb CreateRules --RegionId '.$region_id.' --LoadBalancerId '.$slb_id.' --ListenerPort '.$port.' --RuleList \''.$rule.'\'';
		
		$rs = $this->exec($cmd);
		$rs = json_decode($rs , 1);
		if(isset($rs['Rules']['Rule']['RuleId'])){
			return true;
		}else{
			return false;
		}
	}
	public function rm_slb_forward_rule($region_id , $rule_id){
		$s = json_encode([$rule_id]);
		$cmd = '/usr/local/bin/aliyun -p product slb DeleteRules --RegionId '.$region_id.' --RuleIds \''.$s.'\'';
		$rs = $this->exec($cmd);
		$rs = json_decode($rs , 1);
		// if(isset($rs['Rules']['Rule']['RuleId'])){
			return true;
		// }else{
		// 	return false;
		// }
	}



	private function exec($cmd){
		$time = time();
		$rs = self::_run_cmd($cmd);
		$time = time()-$time;
		Log::info('Dns:'.$cmd.' '. $time .' '.$rs);

		return $rs;
	}
	static private function _run_cmd($cmd){
		$fp = popen($cmd , 'r');
		while (!feof($fp)){
			$rs .= fread($fp , 4096);
		};
		return $rs;
	}
}